from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import uuid
import json
import time
from apps.user.models import User


class ResponseLoggerMiddleware(MiddlewareMixin):
    def process_response(self, request, response: HttpResponse):
        ruid = request.path
        try:
            json.loads(response.content)
            print('[%s]>>> %s-%s' % (ruid, request.path, request.method), request.request_id, response.content.decode('utf-8'))
        except:
            try:
                if '<xml>' in response.content:
                    print('[%s]>>> %s-%s' % (ruid, request.path, request.method), request.request_id)
            except:
                pass
        print('[%s]---------%s End ---------' % (ruid, time.time(),))
        return response


class RequestLoggerMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request_id = uuid.uuid4().hex
        request.request_id = request_id
        ruid = request.path
        print('[%s]--------- START %s %s %s-%s ---------' % (ruid, time.time(), request.request_id, request.path, request.method))
        print('[%s]<<< %s-%s' % (ruid, request.path, request.method), request.request_id, 'Path:', request.path, 'Method:', request.method)
        print('[%s]<<< %s-%s' % (ruid, request.path, request.method), request.request_id, 'Token:', request.META.get('HTTP_AUTHORIZATION', 'NoAuth'))
        try:
            json.loads(request.body.decode('utf-8'))
            print('[%s]<<< %s-%s' % (ruid, request.path, request.method), request.request_id, str(request.body).replace(r'\n', ''))
        except:
            pass